#pragma once
#include <iostream>
#include <string>
#include <mysql/mysql.h>
#include "../comm/httplib.h"
#include <jsoncpp/json/json.h>

#include "head_mysql.hpp"
using namespace std;
using namespace httplib;

// 处理登录请求
void handle_login_test(const httplib::Request &req, httplib::Response &res)
{
    // 解析请求体中的 JSON 数据
    Json::CharReaderBuilder reader;
    Json::Value jsonData;
    std::string body = req.body;
    std::istringstream s(body);
    std::string errs;

    if (!Json::parseFromStream(reader, s, &jsonData, &errs))
    {
        res.status = 400; // Bad Request
        res.set_content("无效 JSON", "text/plain");
        return;
    }

    std::string username = jsonData["username"].asString();
    std::string password = jsonData["password"].asString();

    // 连接到数据库
    MYSQL *conn = connect_db();
    if (conn == nullptr)
    {
        res.status = 500; // Internal Server Error
        res.set_content("数据库连接失败", "text/plain");
        return;
    }

    // 构建 SQL 查询，增加 session_id 字段
    std::string query = "SELECT password, is_verified, session_id FROM users WHERE username = '" + username + "'";

    if (mysql_query(conn, query.c_str()))
    {
        res.status = 500; // Internal Server Error
        res.set_content("查询执行失败", "text/plain");
        mysql_close(conn);
        return;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    if (result == nullptr)
    {
        res.status = 500; // Internal Server Error
        res.set_content("结果检索失败", "text/plain");
        mysql_close(conn);
        return;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (row)
    {
        std::string db_password = row[0] ? row[0] : "";
        int is_verified = row[1] ? std::stoi(row[1]) : 0;
        std::string session_id = row[2] ? row[2] : "";

        if (db_password == password)
        {
            if (is_verified == 1)
            {
                // 设置从数据库获取的 session_id 到 Cookie 中
                res.set_header("Set-Cookie", "sessionid=" + session_id + "; Path=/; Max-Age=3600"); // 设置会话 cookie
                res.status = 200;                                                                   // OK
                res.set_content("登录成功", "text/plain");
            }
            else
            {
                res.status = 403; // Forbidden
                res.set_content("未验证用户", "text/plain");
            }
        }
        else
        {
            res.status = 401; // Unauthorized
            res.set_content("无效的用户名或密码", "text/plain");
        }
    }
    else
    {
        res.status = 401; // Unauthorized
        res.set_content("无效的用户名或密码", "text/plain");
    }

    // 清理
    mysql_free_result(result);
    mysql_close(conn);
}
